package com.atguigu.tingshu.user.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.login.GuiGuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private KafkaService kafkaService;


    /**
     * 修改用户信息
     * @param userInfoVo
     * @return
     */
    @GuiGuLogin
    @Operation(summary = "修改用户信息")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){
        //  获取用户Id
        Long userId = AuthContextHolder.getUserId();
        //  调用服务层方法.
        this.userInfoService.updateUser(userId,userInfoVo);
        //  返回数据
        return Result.ok();

    }

    /**
     * 获取用户信息
     * @return
     */
    @GuiGuLogin
    @Operation(summary = "获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        //  获取用户信息；需要一个条件? userId
        Long userId = AuthContextHolder.getUserId();
        //  调用服务层方法。
        //  UserInfo userInfo = userInfoService.getById(userId);
        //        UserInfo userInfo = userInfoService.getById(userId);
        //        UserInfoVo userInfoVo = new UserInfoVo();
        //        BeanUtils.copyProperties(userInfo,userInfoVo);
        UserInfoVo userInfoVo = this.userInfoService.getUserInfo(userId);
        //  返回数据
        return Result.ok(userInfoVo);
    }

    //	http://127.0.0.1/api/user/wxLogin/wxLogin/0f1hKoHa1gSqdH0kyhHa1zzKzF4hKoHT
    /**
     * 登录方法
     */
    @Operation(summary = "用户登录")
    @GetMapping("/wxLogin/{code}")
    public Result wxLogin(@PathVariable String code){
        //  调用服务层方法.
        WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
        try {
            wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //  获取到了OpenId
        String openId = wxMaJscode2SessionResult.getOpenid();
        //  判断当前用户信息表中是否有这个openId 如果存在，则说明这个用户注册过。直接返回登录成功，如果没有，则注册并初始化账户金额.
        //  select * from user_info where wx_open_id = ?;
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
        if (null == userInfo){
            //  注册.
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openId);
            userInfo.setNickname("听友:"+System.currentTimeMillis());
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            //  保存：
            this.userInfoService.save(userInfo);
            //  发送消息初始化账户信息. user_account 异步形式
            kafkaService.sendMessage(KafkaConstant.QUEUE_USER_REGISTER, userInfo.getId().toString());
        }
        //  登录成功：
        String token = UUID.randomUUID().toString().replaceAll("-","");
        //  String key=token value=userInfo.toString(); 做序列化操作。
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.opsForValue().set(loginKey,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        //  创建map 集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //  返回数据
        return Result.ok(map);
    }

}
